/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
  DefaultFooter,
} from '@ant-design/pro-layout';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useIntl, connect, Dispatch, history } from 'umi';
import { GithubOutlined, WechatOutlined, QqOutlined } from '@ant-design/icons';
import { Result, Button, Modal, Descriptions } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { ConnectState } from '@/models/connect';
import { getMatchMenu } from '@umijs/route-utils';
import logos from '../assets/image/logo.png';

import { GuidedRegistration } from './GuidedRegistration';

import userIcon from '@/assets/image/u4080.png';
import qqimg from '@/assets/image/qqaol.png';
import wximg from '@/assets/image/image.png';
const { info } = Modal;

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);
export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};
/**
 * use Authorized check all menu item
 */
let MenuLists = [
  {
    name: '个人中心',
    key: 'information',
    locale: 'information',
    path: './information',
    children: [
      {
        key: '/information/workbench',
        locale: 'workbench',
        name: '工作台',
        path: '/information/workbench'
      },
      {
        key: '/information/accountInformation',
        locale: 'accountInformation',
        name: '账户信息',
        path: '/information/accountInformation'
      },
      {
        key: '/information/securitySettings',
        locale: 'securitySettings',
        name: '安全设置',
        path: '/information/securitySettings'
      }
    ]
  },
  {
    name: '发稿中心',
    key: 'publishingCenter',
    locale: 'publishingCenter',
    path: './publishingCenter',
    children: [
      {
        key: '/publishingCenter/mediaResources',
        locale: 'mediaResources',
        name: '媒体资源',
        path: '/publishingCenter/mediaResources'
      },
      {
        key: '/publishingCenter/publishManuscript',
        locale: 'publishManuscript',
        name: '发布稿件',
        path: '/publishingCenter/publishManuscript'
      },
      {
        key: '/publishingCenter/myOrder',
        locale: 'myOrder',
        name: '我的订单',
        path: '/publishingCenter/myOrder'
      }
    ]
  },
  {
    name: '资金管理',
    key: 'moneyManagement',
    locale: 'moneyManagement',
    path: './moneyManagement',
    children: [
      {
        key: '/moneyManagement/fundingDetails',
        locale: 'fundingDetails',
        name: '资金明细',
        path: '/moneyManagement/fundingDetails'
      },
      {
        key: '/moneyManagement/myEnvelope',
        locale: 'myEnvelope',
        name: '我的红包',
        path: '/moneyManagement/myEnvelope'
      },
      {
        key: '/moneyManagement/recharge',
        locale: 'recharge',
        name: '充值',
        path: '/moneyManagement/recharge'
      },
      {
        key: '/moneyManagement/invoiceRequest',
        locale: 'invoiceRequest',
        name: '发票申请',
        path: '/moneyManagement/invoiceRequest'
      }
    ]
  },
  {
    name: '媒介中心',
    key: 'mediaCenter',
    locale: 'mediaCenter',
    path: './mediaCenter',
    children: [
      {
        key: '/mediaCenter/orderProcessing',
        locale: 'orderProcessing',
        name: '订单处理',
        path: '/mediaCenter/orderProcessing'
      },
      {
        key: '/mediaCenter/revenueManagement',
        locale: 'revenueManagement',
        name: '收益管理',
        path: '/mediaCenter/revenueManagement'
      },
      {
        key: '/mediaCenter/myResources',
        locale: 'myResources',
        name: '我的资源',
        path: '/mediaCenter/myResources'
      }
    ]
  },
  {
    name: '联系我们',
    key: 'contactUs',
    locale: 'contactUs',
    path: './contactUs',
    children: [
      {
        key: '/contactUs/customerService',
        locale: 'customerService',
        name: 'QQ客服',
        path: '/contactUs/customerService'
      }
    ]
  }
]
const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] => {
  return menuList.filter(item => item.name !== '我的消息').map((item) => {
    const localItem = {
      ...item,
      children: item.children ? menuDataRender(item.children) : undefined,
    };
    // return Authorized.check(item.authority, localItem, null) as MenuDataItem;
    return localItem;
  });
}
  

const defaultFooterDom = (
  <DefaultFooter
    copyright={`${new Date().getFullYear()} 蚂蚁集团体验技术部出品`}
    links={[
      {
        key: 'Ant Design Pro',
        title: 'Ant Design Pro',
        href: 'https://pro.ant.design',
        blankTarget: true,
      },
      {
        key: 'github',
        title: <GithubOutlined />,
        href: 'https://github.com/ant-design/ant-design-pro',
        blankTarget: true,
      },
      {
        key: 'Ant Design',
        title: 'Ant Design',
        href: 'https://ant.design',
        blankTarget: true,
      },
    ]}
  />
);

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const [isModalVisible, setIsModalVisible] = useState(true);
  const {
    dispatch,
    children,
    settings,
    location = {
      pathname: '/',
    },
  } = props;

  const menuDataRef = useRef<MenuDataItem[]>([]);

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
  }, []);
  /**
   * init variables
   */

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
      console.log(111)
    }
  };
  // get children authority
  const authorized = useMemo(
    () =>
      getMatchMenu(location.pathname || '/', menuDataRef.current).pop() || {
        authority: undefined,
      },
    [location.pathname],
  );

  const { formatMessage } = useIntl();

  return (
    <>
      <ProLayout

        title="Digi Hive"
        menuHeaderRender={(logo, title) => (
          <div
            id="customize_menu_header"
            style={{textAlign: 'center',flex: 1}}
          >
            <img src={logos}/>
            <h1 style={{display: 'block',marginTop: 5}}>数字蜂巢Digi Hive</h1>
          </div>
        )}
        formatMessage={formatMessage}
        {...props}
        {...settings}
        onCollapse={handleMenuCollapse}
        onMenuHeaderClick={() => history.push('/')}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl || !menuItemProps.path || menuItemProps.name === "微信客服" || menuItemProps.name === "QQ客服") {
            if(menuItemProps.name === "微信客服"){
              return <div onClick={() => {
                info({
                  title: '添加微信客服',
                  icon: <WechatOutlined />,
                  content: <>
                    <div style={{width: 300,height: 300}}>
                      <img src={wximg} style={{width: 293,height: 300}}/>
                    </div>
                  </>,
                  onOk() {
                    console.log('OK');
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });


              }}><WechatOutlined />微信客服</div>
              
            }else if(menuItemProps.name === "QQ客服"){
              return <div onClick={() => {
                info({
                  title: '添加QQ客服',
                  icon: <WechatOutlined />,
                  content: <>
                    <div style={{width: 300,height: 339}}>
                      <div style={{height: 339}}>
                        <div style={{textAlign: 'center',	padding: '30px 0'}}>
                          <img src={userIcon} style={{width: 160,height: 160}}/>
                        </div>  
                        <div style={{padding:'0 30px'}}>
                          <Descriptions column={1}>
                            <Descriptions.Item label="联系人">李小冉</Descriptions.Item>
                            <Descriptions.Item label="QQ">
                              <a>
                                <img src={qqimg}/>
                              </a>
                              
                              
                            </Descriptions.Item>
                            <Descriptions.Item label="手机号">18810068790</Descriptions.Item>
                          </Descriptions>
                        </div>
                      </div>
                    </div>
                  </>,
                  onOk() {
                    console.log('OK');
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });

              }}><QqOutlined />QQ客服</div>
            } 
            return defaultDom;
          }
          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        breadcrumbRender={(routers = []) => [
          {
            path: '/',
            breadcrumbName: formatMessage({ id: 'menu.home' }),
          },
          ...routers,
        ]}
        itemRender={(route, params, routes, paths) => {
          const first = routes.indexOf(route) === 0;
          return first ? (
            <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
          ) : (
            <span>{route.breadcrumbName}</span>
          );
        }}

        menuDataRender={ (list) => {
          return menuDataRender(list)
        }}
        rightContentRender={() => <RightContent />}
        postMenuData={(menuData) => {
          menuDataRef.current = menuData || [];
          return menuData || [];
        }}
        
      >
        <Authorized authority={authorized!.authority} noMatch={noMatch}>
          {children}
        </Authorized>
      </ProLayout>
      <GuidedRegistration visible={isModalVisible} onCancel={() => setIsModalVisible(false)} />
    </>
  );
};
//      footerRender={() => defaultFooterDom}

export default connect(({ global, settings }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
}))(BasicLayout);
